﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel.DataAnnotations;
using Rhino.Mocks;
using System.Web.Mvc;
using System.Linq.Expressions;

namespace ASPItalia.ModelVirtualCasting.Web.Tests.Utils
{
    public static class ModelTestHelper
    {
        public static Dictionary<string, string> ValidateModel(object model)
        {
            if (model == null)
                throw new ArgumentNullException("model");

            var mocks = new MockRepository();
            var context = mocks.Stub<ControllerContext>(null);

            var validator = ModelValidator.GetModelValidator(
                ModelMetadataProviders.Current.GetMetadataForType(
                    () => model, model.GetType()), context);

            Dictionary<string, string> result = new Dictionary<string, string>();
            foreach (var item in validator.Validate(null))
            {
                result.Add(item.MemberName, item.Message);
            }

            return result;
        }

        public static List<ValidationAttribute> GetValidationAttributes<T>(Expression<Func<T, object>> property)
        {
            var propertyInfo = Helpers.GetMemberInfo(property);

            var attributes = propertyInfo.GetCustomAttributes(typeof(ValidationAttribute), true);

            return new List<ValidationAttribute>(attributes.Cast<ValidationAttribute>());
        }

        public static bool Contains<T>(this IEnumerable<object> items) where T : class
        {
            return GetAttribute<T>(items) != null;
        }

        public static T GetAttribute<T>(this IEnumerable<object> items) where T : class
        {
            var res = items.Where(i => i is T).FirstOrDefault();

            if (res != null)
                return (T)res;

            return null;
        }
    }
}
